/*
    Dao FLTK2
    Copyright (C) 2010 Belousov Oleg <belousov.oleg@gmail.com>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include <fltk/GlWindow.h>
#include <dao.h>

#include "widget.h"
#include "group.h"
#include "glwindow.h"

extern DaoVmSpace  *VmSpace;

using namespace fltk;

class CGlWindow : public GlWindow {
    char init;

    void draw();

public:
    CGlWindow(int x, int y, int w, int h, const char *l=0) : GlWindow(x,y,w,h,l) {
	init = 0;
    }
};

void CGlWindow::draw() {
    DaoCData    	*cdata = (DaoCData*) user_data();
    DaoObject   	*obj = DaoCData_GetObject(cdata);
    DaoVmProcess	*vmp = DaoVmSpace_AcquireProcess(VmSpace);
    DValue      	val;

    if (!valid()) {
	if (!init) {
	    val = DaoObject_GetField(obj, "init");

	    if (val.t == DAO_ROUTINE) {
    		DaoVmProcess_Call(vmp, val.v.routine, obj, NULL, 0);
    		DaoVmSpace_ReleaseProcess(VmSpace, vmp);
    	    }
    	    init = 1;
	}

	val = DaoObject_GetField(obj, "reshape");

	if (val.t == DAO_ROUTINE) {
	    DValue arg1[] = { DValue_NewFloat(w()) };
	    DValue arg2[] = { DValue_NewFloat(h()) };
	    DValue *args[] = { arg1, arg2 };

    	    DaoVmProcess_Call(vmp, val.v.routine, obj, args, 2);
    	    DaoVmSpace_ReleaseProcess(VmSpace, vmp);
    	}
    }

    val = DaoObject_GetField(obj, "draw");

    if (val.t == DAO_ROUTINE) {
        DaoVmProcess_Call(vmp, val.v.routine, obj, NULL, 0);
        DaoVmSpace_ReleaseProcess(VmSpace, vmp);
    }
}

static void glwindow_new(DaoContext *ctx, DValue *p[], int N) {
    int x = (int) p[0]->v.i;
    int y = (int) p[1]->v.i;
    int w = (int) p[2]->v.i;
    int h = (int) p[3]->v.i;

    CGlWindow *ptr;

    ptr = new CGlWindow(x,y, w, h);

    DaoCData *cdata = DaoContext_PutCData(ctx, ptr, &glwindowTyper);

    init_callback(ptr, cdata);
};

//

static DaoFuncItem glwindowMeth[] = {
    { glwindow_new, 		"fltk_glwindow(x:int, y:int, w:int, h:int)" },
    { NULL, NULL }
};

DaoTypeBase glwindowTyper = {
    "fltk_glwindow",
    NULL,
    NULL,              		/* no constant number */
    glwindowMeth,               /* methods */
    { &groupTyper, NULL },      /* parent type */
    { NULL },
    NULL,
    NULL                        /* free by free() */
};
